package com.cn.wanxi.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet("/code")
public class Code extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建空白图片
        BufferedImage image = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
        //获取图片画笔
        Graphics g = image.getGraphics();
        Random random = new Random();//设置随机数
        //设置画笔颜色
        g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
        //绘制矩形背景
        g.fillRect(0,0,100,30);
        //调用自定义的方法获取长度为5的字母数字组合的字符串
        String number = getNumber(4);
        System.out.println(number);
        req.getSession().setAttribute("code",number);
        g.setColor(new Color(0,0,0));
        g.setFont(new Font("宋体",Font.BOLD,24));
        //设置颜色字体后，绘制字符串
        g.drawString(number,4,25);
        //绘制18条干扰线
        for (int i = 0; i < 18; i++) {
            g.setColor(
                    new Color(
                            random.nextInt(255),
                            random.nextInt(255),
                            random.nextInt(255),
                            random.nextInt(255)
                    )
            );
            g.drawLine(
                    random.nextInt(100),
                    random.nextInt(30),
                    random.nextInt(100),
                    random.nextInt(30)
                    //直线参数（a,b,x,y）a，b代表起点，x，y代表终点
            );
        }
        resp.setContentType("image/ jpeg");
        OutputStream ops = resp.getOutputStream();
        ImageIO.write(image,"jpeg",ops);
        ops.close();
    }

    /**
     * 字符串的拼接
     * @param size
     * @return
     */
    private String getNumber(int size) {
        //因为英文字母Oo和数字0，英文字母l和数字1过于相似不好辨认，因此生成验证码时去除掉这几个字符
        String str = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
        StringBuilder number = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < size; i++) {
            number.append(str.charAt(r.nextInt(str.length())));
        }
        return number.toString();
    }
}
